﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using qltscd.Helper;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web.Routing;

namespace qltscd.Controllers
{ 
    public class DanhMucHopDongController : BaseController
    {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ViewResult Index()
        {
            Session[SessionConstants.ERROR_MESSAGE] = string.Empty;
            DanhMucHopDongScreenClient screen = new DanhMucHopDongScreenClient();
            if (Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT] != null)
            {
                screen = (DanhMucHopDongScreenClient)Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT];
            }
            SearchHopDong(screen);
            return View(screen);
        }

        [HttpPost]
        public ActionResult Index(DanhMucHopDongScreenClient screen)
        {
            SearchHopDong(screen);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index()
        {
            DanhMucHopDongScreenClient screen = new DanhMucHopDongScreenClient();
            if (Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT] != null)
            {
                screen = (DanhMucHopDongScreenClient)Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT];
            }
            SearchHopDong(screen);
            return View(new GridModel(screen.DSHopDong));
        }

        public ActionResult ShowPdf () {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucHopDong.rpt";
            rpt.Load();
            rpt.SetDatabaseLogon("sa", "sa");
            //rpt.SetDataSource(db.DanhMucHopDongs);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }

        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucHopDongs
                       select n;

            myTable.Columns.Add("Mã Hợp Đồng");
            myTable.Columns.Add("Số Hợp Đồng");
            myTable.Columns.Add("Ngày Ký");
            myTable.Columns.Add("Người Ký");
            myTable.Columns.Add("Nội Dung");
            myTable.Columns.Add("Tổng Kinh Phí");
            myTable.Columns.Add("Ngày Thực Hiện");
            myTable.Columns.Add("Thời Gian Thực Hiện");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaHopDong.ToString(), n.SoHopDong.ToString(), n.NgayKy, n.NguoiKy, n.NoiDung, n.TongKinhPhi, n.NgayThucHien, n.ThoiGianThucHien);
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucHopDong.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC HỢP ĐỒNG\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch
            {

            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucHopDong", "application/ms-excel", "BaoCaoDanhMucHopDong.xls");
        }

        public ActionResult Create () {
            string mahopdong = Request.QueryString["MaHopDong"];
            Models.BaseClient.DanhMucHopDong hopdong = new Models.BaseClient.DanhMucHopDong() { IdentityHopDong = -1 };
            if (mahopdong != null) {
                try {
                    DanhMucHopDong hd = db.DanhMucHopDongs.Single(i => i.MaHopDong == mahopdong);
                    ObjectHelper.Copy(hd, hopdong);
                    hopdong = SearchThietBiHopDong(hopdong.IdentityHopDong);
                } catch { }
            } else {
                Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT] = hopdong;
            }
            ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu", hopdong.IdentityKieu);
            ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hopdong.IdentityLoaiTien);
            ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hopdong.IdentityNguoiDung);
            ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hopdong.IdentityNhaCungCap);
            ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hopdong.IdentityNuocSanXuat);
            return View(hopdong);
        }

        [GridAction]
        public ActionResult _Create () {
            if (Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT] != null) {
                Models.BaseClient.DanhMucHopDong hopdong = (Models.BaseClient.DanhMucHopDong)Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT];
                if (hopdong.IdentityHopDong != -1) {
                    hopdong = SearchThietBiHopDong(hopdong.IdentityHopDong);
                }
                ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang");
                return View(new GridModel(hopdong.DSThietBi));                
            } else {
                Models.BaseClient.DanhMucHopDong hopdong = new Models.BaseClient.DanhMucHopDong() { IdentityHopDong = -1 };
                Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT] = hopdong;
                ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang");
                return View(new GridModel(hopdong.DSThietBi));
            }
        }

        public ActionResult SuaHopDong()
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucHopDong hd = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == iden);
                Models.BaseClient.DanhMucHopDong hdC = new Models.BaseClient.DanhMucHopDong();
                ObjectHelper.Copy(hd, hdC);
                ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu",hdC.IdentityKieu);
                ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hdC.IdentityLoaiTien);
                ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hdC.IdentityNguoiDung);
                ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hdC.IdentityNhaCungCap);
                ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hdC.IdentityNuocSanXuat);
                return View(hdC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult ThongTinHopDong(int id)
        {
            DanhMucHopDong hd = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == id);
            return View(hd);
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult SuaHopDong(Models.BaseClient.DanhMucHopDong hdC)
        {
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucHopDong h = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == hdC.IdentityHopDong);
                if (hdC.MaHopDong != h.MaHopDong) {
                    if (db.DanhMucHopDongs.Count(i => i.MaHopDong == hdC.MaHopDong) > 0) {
                        ViewData[SessionConstants.ERROR_MESSAGE] = "Mã " + hdC.MaHopDong + " đã tồn tại";
                        return View(hdC);
                    }
                }
                ObjectHelper.Copy(hdC, h);
                db.ObjectStateManager.ChangeObjectState(h, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu", hdC.IdentityKieu);
            ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hdC.IdentityLoaiTien);
            ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hdC.IdentityNguoiDung);
            ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hdC.IdentityNhaCungCap);
            ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hdC.IdentityNuocSanXuat);
            return View(hdC);
        }

        [HttpPost]
        public ActionResult Create (Models.BaseClient.DanhMucHopDong hopdong) {
            if (ModelState.IsValid)
            {
                DanhMucHopDong hd = new DanhMucHopDong();
                if (hopdong.IdentityHopDong == -1)
                {
                    if (db.DanhMucHopDongs.Count(o => o.MaHopDong == hopdong.MaHopDong) > 0)
                    {
                        ViewData[SessionConstants.ERROR_MESSAGE] = "Mã hợp đồng " + hopdong.MaHopDong + " đã tồn tại";
                        ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu", hopdong.IdentityKieu);
                        ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hopdong.IdentityLoaiTien);
                        ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hopdong.IdentityNguoiDung);
                        ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hopdong.IdentityNhaCungCap);
                        ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hopdong.IdentityNuocSanXuat);
                        return View(hopdong);
                    }
                    ObjectHelper.Copy(hopdong, hd);
                    db.DanhMucHopDongs.AddObject(hd);
                }
                else
                {
                    hd = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == hopdong.IdentityHopDong);//lấy 1 thằng
                    if (hopdong.MaHopDong != hd.MaHopDong)
                    {
                        if (db.DanhMucHopDongs.Count(o => o.MaHopDong == hopdong.MaHopDong) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã hợp đồng " + hopdong.MaHopDong + " đã tồn tại";
                            ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu", hopdong.IdentityKieu);
                            ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hopdong.IdentityLoaiTien);
                            ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hopdong.IdentityNguoiDung);
                            ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hopdong.IdentityNhaCungCap);
                            ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hopdong.IdentityNuocSanXuat);
                            return View(hopdong);
                        }
                    }
                    ObjectHelper.Copy(hopdong, hd);
                    db.ObjectStateManager.ChangeObjectState(hd, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("Create");
            }
            return View(hopdong);
            ViewBag.IdentityKieu = new SelectList(db.DanhMucKieux.OrderBy(i => i.TenKieu), "IdentityKieu", "TenKieu", hopdong.IdentityKieu);
            ViewBag.IdentityLoaiTien = new SelectList(db.DanhMucLoaiTiens.OrderBy(i => i.TenLoaiTien), "IdentityLoaiTien", "TenLoaiTien", hopdong.IdentityLoaiTien);
            ViewBag.IdentityLyDoTang = new SelectList(db.DanhMucLyDoTangs.OrderBy(i => i.TenLyDoTang), "IdentityLyDoTang", "TenLyDoTang", hopdong.IdentityNguoiDung);
            ViewBag.IdentityNhaCungCap = new SelectList(db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap), "IdentityNhaCungCap", "TenNhaCungCap", hopdong.IdentityNhaCungCap);
            ViewBag.IdentityNuocSanXuat = new SelectList(db.DanhMucNuocSanXuats.OrderBy(i => i.TenNuocSanXuat), "IdentityNuocSanXuat", "TenNuocSanXuat", hopdong.IdentityNuocSanXuat);
            return View(hopdong);
        }
        public ActionResult XoaHopDong()
        {
            string id = Request.QueryString["id"];
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucHopDong hd = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == iden);
                    db.DanhMucHopDongs.DeleteObject(hd);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }
        #endregion

        #region Helper Section
        private void SearchHopDong(DanhMucHopDongScreenClient screen)
        {
            if (Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT] != null)
            {
                screen = (DanhMucHopDongScreenClient)Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT];
            }
            else
            {
                screen = new DanhMucHopDongScreenClient();
            }
            screen.DSHopDong.Clear();
            var list = db.DanhMucHopDongs.OrderBy(i => i.SoHopDong).ToList();
            foreach (DanhMucHopDong hd in list)
            {
                qltscd.Models.BaseClient.DanhMucHopDong hdClient = new Models.BaseClient.DanhMucHopDong();
                ObjectHelper.Copy(hd, hdClient);
                DanhMucThietBi thietbi = db.DanhMucThietBis.FirstOrDefault(i => i.IdentityHopDong == hdClient.IdentityHopDong);
                if (thietbi != null) {
                    hdClient.TiGia = thietbi.TiGia;
                }
                screen.DSHopDong.Add(hdClient);
            }
            Session[SessionScreenContansts.HOP_DONG_SCREENCLIENT] = screen;
        }

        private Models.BaseClient.DanhMucHopDong SearchThietBiHopDong (int IDHopDong) {
            try {
                DanhMucHopDong hopdong = db.DanhMucHopDongs.Single(i => i.IdentityHopDong == IDHopDong);
                Models.BaseClient.DanhMucHopDong hopdongClient = new Models.BaseClient.DanhMucHopDong() { IdentityHopDong = -1 };
                var DSThietBi = db.DanhMucThietBis.Where(i => i.IdentityHopDong == IDHopDong);
                hopdongClient.DSThietBi.Clear();
                foreach (DanhMucThietBi thietbi in DSThietBi) {
                    Models.BaseClient.DanhMucThietBi thietbiClient = new Models.BaseClient.DanhMucThietBi() { IdentityHopDong = -1 };
                    ObjectHelper.Copy(thietbi, thietbiClient);
                    thietbiClient.LyDoTang = db.DanhMucLyDoTangs.Single(i => i.IdentityLyDoTang == thietbiClient.IdentityLyDoTang).TenLyDoTang;
                    thietbiClient.NSX = thietbiClient.NamSanXuat.Value.Year;
                    thietbiClient.NCC = thietbiClient.NamCungCap.Value.Year;

                    hopdongClient.DSThietBi.Add(thietbiClient);
                }
                Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT] = hopdongClient;
                return hopdongClient;
            } catch (NullReferenceException) {
                Models.BaseClient.DanhMucHopDong hd = new Models.BaseClient.DanhMucHopDong() { IdentityHopDong = -1 };
                Session[SessionScreenContansts.DanhMucHopDong_ThietBi_SCREENCLIENT] = hd;
                return hd;
            }
        }
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}